package jvm;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project Java_base
 * @create 2017-05-05 16:17
 **/
public class FinalizeEscapeGC {
    public static FinalizeEscapeGC Savv_hook = null;

    public static void main(String[] args) throws Exception {
        Savv_hook = new FinalizeEscapeGC();
        //对象第一次成功拯救自己
        Savv_hook = null;
        System.gc();
        //因为finalize方法优先级别很低，暂时0.5s等待它
        Thread.sleep(500);
        if (Savv_hook != null) {
            Savv_hook.isAlive();
        } else {
            System.out.println("no,I am dead :(");
        }
        System.out.println("因为一个对象的finalize()只会被系统自动调用一次，所以下一次再次GC的时候会被干了。");

        //下面这段代码与上面的完全相同，但是这次自救失败了
        Savv_hook = null;
        System.gc();
        //因为finalize方法优先级别很低，暂时0.5s等待它
        Thread.sleep(500);
        if (Savv_hook != null) {
            Savv_hook.isAlive();
        } else {
            System.out.println("no,I am dead :(");
        }
    }

    public void isAlive() {
        System.out.println("yes,i am still alive");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize method executed!");
        Savv_hook = this;
    }
}
